package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.GradeBean;
import com.project.bean.LogBean;
import com.project.bean.RoleBean;
import com.project.bean.UserBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.ILogMapper;
import com.project.mapper.IRoleMapper;
import com.project.mapper.IUserMapper;
import com.project.service.IUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private IUserMapper userMapper;
    @Autowired
    private ILogMapper logMapper;
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;

    @Override
    public UserBean login(String userName, String password) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_userName",userName);
        qw.eq("u_password",password);
        UserBean userBean = userMapper.selectOne(qw);
        if (userBean !=null){
            DateTimeFormatter dtf =DateTimeFormatter.ofPattern("HH:mm");
            String content = String.format("用户 %s 在 %s 登录系统", userBean.getRealName(), dtf.format(LocalDateTime.now()));
            logMapper.insert(new LogBean(content));
        }
        return userBean;

    }

    @Override
    public UserBean findByName(String userName) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_userName", userName);
        UserBean user = userMapper.selectOne(qw);
        if (user != null) {
            //查找权限
            user.setGradeList(gradeMapper.findByUserId(user.getUserId()));
            //查找角色
            user.setRoleList(roleMapper.findByUserId(user.getUserId()));
        }

        return user;
    }

    @Override
    public IPage<UserBean> findByItem(Integer pageNO, String userName) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        if (userName != null && userName.length() != 0){
            qw.like("u_userName",userName);
        }
        return userMapper.selectPage(new Page<>(pageNO,3),qw);
    }
    @Override
    public boolean add(UserBean user, Integer[] roleIdArr) {
        QueryWrapper<UserBean> qw = new QueryWrapper<>();
        qw.eq("u_userName",user.getUserName());
        if (userMapper.selectCount(qw) ==0){
            user.setSalt(this.getSalt());
            Md5Hash md5Hash = new Md5Hash(user.getPassword(), user.getSalt(), 1024);
            user.setPassword(md5Hash.toHex());
            userMapper.insert(user);
            userMapper.addRoleList(user.getUserId(),roleIdArr);
            return true;
        }
        return false;
    }

    @Override
    public void del(Integer userId) {
        userMapper.del(userId);
        userMapper.deleteById(userId);
    }

    @Override
    public UserBean findById(Integer userId) {
        UserBean userBean = userMapper.selectById(userId);
        userBean.setRoleList(roleMapper.findByUserId(userId));
        return userBean;
    }

    @Override
    public void update(Integer userId, Integer[] roleIdArray) {
        userMapper.del(userId);
        userMapper.addRoleList(userId,roleIdArray);
    }

    @Override
    public boolean updatePwd(Integer userId, String password,String oldPassword) {
        UserBean user = userMapper.selectById(userId);
        String old = new Md5Hash(oldPassword,user.getSalt(),1024).toHex();
        if (!user.getPassword().equals(old)){
            return false;
        }
        user.setSalt(this.getSalt());
        String pwd = new Md5Hash(password, user.getSalt(), 1024).toHex();
        user.setPassword(pwd);
        userMapper.updateById(user);
        return true;
    }

    private String getSalt() {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()";
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int index = (int) (Math.random() * str.length());
            sb.append(str.charAt(index));
        }
        return sb.toString();
    }
}
